<template>
  <div>
    <Card>
      <div class="p-relative">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">
        <template slot-scope="{ row, index }" slot="estate">
          <i-switch size="large" v-model="row.estate==1?true:false" @on-change='estate(row,index)' true-color="#13ce66"
            false-color="#ff4949">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">

            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
             <Button v-if="!row.is_build" type='primary' @click="build(row, index)" size='small'>生成</Button>
            <!-- <Button type='error' @click="del(row, index)" size='small'>删除</Button> -->

          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>

    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='700'>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
        <FormItem label="名称" prop="name">
          <Input placeholder="请输入优惠券名称" v-model="formValidate.name"></Input>
        </FormItem>

        <FormItem label="领取人群">
          <Select placeholder="请选择领取人群" :disabled="formValidate.is_build" v-model='formValidate.receive_condition'>
            <Option v-for="item in receive_condition" :value="item.value" :key="item.label">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="优惠券类型" prop="limit_type">
          <Select placeholder="请选择优惠券类型" :disabled="formValidate.is_build" v-model='formValidate.type'  >
            <Option v-for="(item,index) in type" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
       <!-- <FormItem label="是否地叠加使用">
          <RadioGroup v-model="formValidate.is_overlay">
            <Radio :label="item.value" :key='item.label' v-for="(item,index) in overlayType">{{item.label}}</Radio>
          </RadioGroup>
        </FormItem> -->
        <FormItem label="使用限制" prop="limit_type">
          <Select placeholder="请选择使用限制" :disabled="formValidate.is_build" v-model='formValidate.limit_type' @on-change=''>
            <Option v-for="(item,index) in limit_type" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="可使用项目" prop="category_id">
          <CheckboxGroup v-model="formValidate.category_id"  >
            <Checkbox :label="item.id" border :disabled="formValidate.is_build" v-for="(item,index) in categoryList">{{item.name}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="使用规则" prop="use_rules">
          <Input placeholder="请输入使用规则" v-model="formValidate.use_rules"></Input>
        </FormItem>
        <FormItem label="优惠券金额/折扣" prop="coupon_money">
          <Input placeholder="请输入优惠券金额或折扣 例:8折则输入8 " :disabled="formValidate.is_build" v-model="formValidate.coupon_money"></Input>
        </FormItem>
        <FormItem label="满额可用" prop="spend_money">
          <Input placeholder="请输入满额可用 0则表示无门槛 任何金额都可使用" :disabled="formValidate.is_build" v-model="formValidate.spend_money"></Input>
        </FormItem>
        <FormItem label="发放数量" prop="send_num">
          <Input placeholder="请输入发放数量" :disabled="formValidate.is_build" v-model="formValidate.send_num"></Input>
        </FormItem>

        <FormItem label="使用开始时间" prop='use_start_at'>
          <Col span="12">
          <Date-picker v-model='formValidate.use_start_at' :disabled="formValidate.is_build" type="datetime" placeholder="选择日期和时间" style="width: 200px">
          </Date-picker>
          </Col>
        </FormItem>
        <FormItem label="使用到期时间" prop='use_expire_at'>
          <Col span="12">
          <Date-picker v-model='formValidate.use_expire_at' :disabled="formValidate.is_build"  type="datetime" placeholder="选择日期和时间" style="width: 200px">
          </Date-picker>
          </Col>
        </FormItem>
        <FormItem label="领取开始时间" prop='receive_start_at'>
          <Col span="12">
          <Date-picker v-model='formValidate.receive_start_at' :disabled="formValidate.is_build" type="datetime" placeholder="选择日期和时间"
            style="width: 200px"></Date-picker>
          </Col>
        </FormItem>
        <FormItem label="领取结束时间" prop='receive_expire_at'>
          <Col span="12">
          <Date-picker v-model='formValidate.receive_expire_at' :disabled="formValidate.is_build" type="datetime" placeholder="选择日期和时间"
            style="width: 200px"></Date-picker>
          </Col>
        </FormItem>

        <FormItem label="自动发放">
          <RadioGroup v-model="formValidate.is_auto"  >
            <Radio :disabled="formValidate.is_build" label="1">是</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
            <Radio :disabled="formValidate.is_build" label="0">否</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
          </RadioGroup>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>



    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

    <!-- 确认生成优惠券弹窗 -->
    <Modal v-model="buildModal" title="提示" width="350" >
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />此次操作不可逆，确定生成此优惠券？</p>
      <div slot="footer">
        <Button @click='buildModal=false'>取消</Button>
        <Button type="primary" @click='confirmBuild'>确定</Button>
      </div>
    </Modal>
    <Modal v-model="waitModal" title="提示" width="250" >
      <p class="font16">
        生成中请耐心等待,不要做任何操作导致生成失败..
      </p>
  <div slot="footer">

      </div>
    </Modal>

  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'

  // 接口
  import {
    getList,
    add,
    put,
    del,
    build,
    change

  } from '@/api/marketing-group/coupon'
  import {
    tableOption
  } from '../../../data/marketing-group/coupon.js'
  import Tables from '_c/tables'

  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {
      let _this = this
      this.$nextTick(function() {
        // 权限校验
        _this.role_add = permission(this.roles, 'coupon/add')
        _this.role_edit = permission(this.roles, 'coupon/edit')
        _this.role_build  = permission(this.roles, 'coupon/build')

      })
      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({

        roles: state => state.user.roles

      }),
    },
    data() {
      return {
        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,
        waitModal:false,
        role_build:false,
        // 上传
        tableOption: tableOption,
        delId: '',
        data: {
          related: [],
          store: [],
          list: [{
            name: '测试数据',
            id: 1
          }],
          class: []
        },
        createTitle: ' ',
        isAdd: true, // 新增true,修改false
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态

        loadingText: '',

        // 查询参数
        searchObj: {
          name: ''

        },
        // 分页
        page: {
          pageSize: 8,
          current: 1,
          total: 0
        },

        // 分页end
        // 弹窗状态
        createModal: false, // 新增，修改弹窗
        delModal: false, // 删除弹窗

        formValidate: {
          name: '',
          coupon_money: null,
          spend_money: null,
          receive_condition: null, // 领取人群
          is_overlay: 0, // 是否叠加
          limit_type: null,
          type: null,
          use_start_at: null, // 使用开始时间
          use_expire_at: null, // 使用结束
          receive_start_at: null,
          receive_expire_at: null,
          estate: null,
          category_id: [],
          send_num: '',
          use_rules: '',
          is_auto:'0'
        },

        ruleValidate: {

        },
        overlayType: [{
            label: '否',
            value: 0
          },
          {
            label: '是',
            value: 1
          }
        ],
        receive_condition: [{
            label: '全体授权用户',
            value: 0
          },
          {
            label: '首次登录',
            value: 1
          },
          // {
          //   label: '链接领取',
          //   value: 2
          // },
          // {
          //   label: '兑换领取码',
          //   value: 3
          // }
        ],
        limit_type: [{
            label: '无限制',
            value: 0
          },
          {
            label: '订场',
            value: 1
          },
          {
            label: '课程',
            value: 2
          },
          // {
          //   label: '课程单品',
          //   value: 3
          // },
          // {
          //   label: '购物',
          //   value: 4
          // },
        ],
        type: [{
            label: '满减',
            value: 0
          },
          {
            label: '折扣',
            value: 1
          },

        ],
        categoryList: [],
        buildId:0,
        buildModal:false,
        // showList
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
          size: this.page.size,
          name: this.searchObj.name
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.categoryList = result.categoryList

          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },

      detail(row) {
        this.detailModal = true;
        this.formValidate = JSON.parse(JSON.stringify(row))

        this.getMakeData();
      },

      changepage(e) {
        this.page.current = e
        this.getList()
      },


      // 新增
      create() {
        if (!this.role_add) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true

        this.createTitle = '添加优惠券'
        this.isAdd = true
        this.formValidate = {} // 表单重置

        this.formValidate.is_overlay = 0;
        this.formValidate.is_auto = '0';
        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        if (!this.role_edit) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true
        this.createTitle = '编辑运动卡'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
        this.formValidate.limit_type = parseInt(this.formValidate.limit_type);
        this.formValidate.type = parseInt(this.formValidate.type);
        this.formValidate.estate = this.formValidate.estate.toString();
        this.formValidate.is_auto = this.formValidate.is_auto.toString();
        let tempArr = this.formValidate.category_id.split(',');
        this.formValidate.category_id = [];
        for (var i in tempArr) {
          this.formValidate.category_id.push(parseInt(tempArr[i]));
        }

        this.handleReset('formValidate') // 验证重置
      },

      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      // 刷新
      refresh() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 重置
      reset() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.getList()
      },

      save(name) {

        let _this = this

        this.$refs[name].validate((valid) => {

          if (valid) {

            if (_this.isAdd) {

              // 新增
              let obj = {
                name: _this.formValidate.name,
                coupon_money: _this.formValidate.coupon_money,
                spend_money: _this.formValidate.spend_money,
                receive_condition: _this.formValidate.receive_condition,
                is_overlay: _this.formValidate.is_overlay,
                limit_type: _this.formValidate.limit_type,
                type: _this.formValidate.type,
                use_start_at: _this.formValidate.use_start_at,
                use_expire_at: _this.formValidate.use_expire_at,
                receive_start_at: _this.formValidate.receive_start_at,
                receive_expire_at:_this.formValidate.receive_expire_at,

                category_id: _this.formValidate.category_id,
                send_num: _this.formValidate.send_num,
                use_rules: _this.formValidate.use_rules

              }

              // 新增接口
              add(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                id: _this.formValidate.id,
                name: _this.formValidate.name,
                coupon_money: _this.formValidate.coupon_money,
                spend_money: _this.formValidate.spend_money,
                receive_condition: _this.formValidate.receive_condition,
                is_overlay: _this.formValidate.is_overlay,
                limit_type: _this.formValidate.limit_type,
                type: _this.formValidate.type,
                use_start_at: _this.formValidate.use_start_at,
                use_expire_at: _this.formValidate.use_expire_at,
                receive_start_at: _this.formValidate.receive_start_at,
                receive_expire_at:_this.formValidate.receive_expire_at,

                category_id: _this.formValidate.category_id,
                send_num: _this.formValidate.send_num,
                use_rules: _this.formValidate.use_rules

              }

              // 修改接口
              put(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
     //确认生成优惠券此操作不可逆
     build(row,index){
       if (!this.role_build) {
         let config = {
           content: '您没有操作权限',
           background: true
         }
         this.$Message.error(config)
         return
       }
       this.buildId=row.id
       this.buildModal = true;
     },
     //生成优惠券
     confirmBuild(){

       let _this = this
       let params = {
         id: _this.buildId

       }
       this.buildModal=false
       this.waitModal = true;
       build(params)
         .then(res => {
           console.log(res)
           if (res.data.status == 1) {
              _this.waitModal = false;
              _this.buildId=''
              _this.getList()
               _this.$Message.success('生产成功！')
           } else {

           }
         }).catch(function(error) {
           // 异常
           console.log(error)
         })
     },
     estate(row, index) {

       let _this = this;
       let obj = {
         id: row.id,
         act: 'estate',
         value: row.estate == 1 ? 0 : 1
       }

       // 修改状态
       change(obj).then(res => {
         if (res.data.status == 1) {
           _this.$Message.success('操作成功')
           _this.data.list[index].estate = obj.value;
           // _this.getList();
         } else {
           //响应拦截里处理
         }
       }).catch(function(error) {
         //异常
         console.log(error)
       })
     },

    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
